package com.ruoyi.cms.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.member.domain.MemberLike;
import com.ruoyi.member.service.IMemberLikeService;
import com.ruoyi.cms.service.IShortVideoService;

/**
 * 短视频点赞Controller
 *
 * @author ruoyi
 * @date 2025-10-24
 */
@RestController
@RequestMapping("/short/member/like")
public class ShortLikeController extends BaseController
{
    @Autowired
    private IMemberLikeService memberLikeService;

    @Autowired
    private IShortVideoService shortVideoService;

    /**
     * 获取短视频点赞状态
     */
    @GetMapping("/status")
    public AjaxResult getStatus(@RequestParam Integer shortId)
    {
        try {
            Long userId = SecurityUtils.getUserId();
            boolean isLiked = memberLikeService.checkLiked(userId, shortId);
            return AjaxResult.success(isLiked);
        } catch (Exception e) {
            // 未登录返回false
            return AjaxResult.success(false);
        }
    }

    /**
     * 点赞短视频
     */
    @PostMapping
    public AjaxResult like(@RequestBody MemberLike memberLike)
    {
        Long userId = SecurityUtils.getUserId();
        memberLike.setUserId(userId);

        // 检查是否已点赞
        if (memberLikeService.checkLiked(userId, memberLike.getShortId())) {
            return AjaxResult.error("已点赞，请勿重复操作");
        }

        // 添加点赞记录
        int result = memberLikeService.insertMemberLike(memberLike);
        if (result > 0) {
            // 增加短视频点赞数
            shortVideoService.increaseLikeCount(memberLike.getShortId().longValue());
            return AjaxResult.success("点赞成功");
        }
        return AjaxResult.error("点赞失败");
    }

    /**
     * 取消点赞短视频
     */
    @PostMapping("/cancel")
    public AjaxResult cancelLike(@RequestBody MemberLike memberLike)
    {
        Long userId = SecurityUtils.getUserId();

        int result = memberLikeService.cancelLike(userId, memberLike.getShortId());
        if (result > 0) {
            // TODO: 减少短视频点赞数（需要添加方法）
            return AjaxResult.success("取消点赞成功");
        }
        return AjaxResult.error("取消点赞失败");
    }

    /**
     * 获取用户点赞列表
     */
    @GetMapping("/list")
    public AjaxResult list()
    {
        Long userId = SecurityUtils.getUserId();
        MemberLike query = new MemberLike();
        query.setUserId(userId);
        return AjaxResult.success(memberLikeService.selectMemberLikeList(query));
    }
}
